package com.bdqn.membersystem.controller;


import com.bdqn.membersystem.common.Constants;
import com.bdqn.membersystem.pojo.AuUser;
import org.apache.log4j.Logger;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @PackgeName: com.bdqn.membersystem.controller
 * @ClassName: BaseController
 * @Author: 汤武琪
 * Date: 2020/4/16 23:03
 * project name: menber-system
 * @Version:
 * @Description:
 */

public class BaseController {
    private Logger logger = Logger.getLogger(BaseController.class);

    private AuUser cuurentUser;

    public AuUser getCuurentUser(){
        if (null ==this.cuurentUser){
            HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = request.getSession(false);
            if (null !=session){
                cuurentUser = (AuUser)session.getAttribute(Constants.SESSION_USER);
            }else {
                cuurentUser = null;
            }
        }
        return cuurentUser;
    }
    public void setCuurentUser(AuUser cuurentUser){
        this.cuurentUser = cuurentUser;
    }

    /**
     * 日期国际化
     */
    @InitBinder
    public void InitBinder(WebDataBinder dataBinder){
        dataBinder.registerCustomEditor(Date.class,new PropertyEditorSupport(){
            @Override
            public void setAsText(String value){
               try {
                   setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
               }catch (ParseException e){
                   e.printStackTrace();
                   setValue(null);
               }
            }
            @Override
            public String getAsText(){
                return new SimpleDateFormat("yyyy-MM-dd").format((Date)getValue());
            }
        });
    }
}
